package com.lazyfish.bootcm.service;

import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Strings.isNullOrEmpty;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.lazyfish.bootcm.config.properties.CustomerManagerProperties;
import com.lazyfish.bootcm.dao.CustomerDao;
import com.lazyfish.bootcm.entity.Customer;
@Service
public class CustomerServiceImpl implements CustomerService{
    @Autowired
    private CustomerDao customerDao;
    private final List<String> statisticsColname;
    @Autowired
    public CustomerServiceImpl(CustomerManagerProperties properties) {
		this.statisticsColname = properties.getStatisticsColname();
	}
    
    
    public Map<String, Object> getStatistics() {
    	Map<String, Object> res = Maps.newLinkedHashMap();
    	res.put("total", customerDao.numberOfCustomer(null, null, null, null));
    	statisticsColname.forEach(col -> res.put(col, customerDao.groupCounter(col)));
    	return res;
    }
    
    @Override
    public Map<String, Object> getCustmerListBySelect(String source, String industry,
    		Integer level, String pattern, 
    		Integer pageNum, Integer pageLen) {
    	pageNum = firstNonNull(pageNum, 1);
    	pageLen = firstNonNull(pageLen, 5);
    	pattern = isNullOrEmpty(pattern) ? null : "%" + pattern + "%";
    	List<Customer> list = customerDao.getCustmerListBySelect(
    			source,industry,level,pattern, pageLen * (pageNum - 1), pageLen);
    	return getPageResult(list, pageNum, pageLen, 
    			customerDao.numberOfCustomer(source, industry, level, pattern));
    }

    protected Map<String, Object> getPageResult(List<Customer> list, int pageNum, int pageLen, double totals) {
    	Map<String, Object> res = Maps.newLinkedHashMap();
    	res.put("list", list);
    	res.put("pageNum", pageNum);
    	res.put("pageLen", pageLen);
    	res.put("pages", (int)Math.ceil(totals / pageLen));
    	return res;
    }
    
    @Override
    public int deleteCustomer(int id) {
        return customerDao.deleteCustmer(id);
    }

    @Override
    public int AddCustomer(Customer customer) {
        return customerDao.AddCustomer(customer);
    }

    @Override
    public int ModifyCustomer(Customer customer) {
        return customerDao.ModifyCustomer(customer);
    }
}
